﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using LibUsbDotNet.DeviceNotify;
using LibUsbDotNet;
using LibUsbDotNet.Main;
using LibUsbDotNet.LibUsb;
using System.Windows.Forms.DataVisualization.Charting;

namespace USBComm
{
    public partial class Form1 : Form
    {
        const int myPID = 0x6002; // 产品ID
        const int myVID = 0x2D95; // 供应商ID
        Boolean EnableInt = false; // 是否使用中断接收
        public static UsbEndpointWriter writer = null; // 数据写入
        public static UsbEndpointReader reader = null; // 数据读取
        public static UsbDevice MyUsbDevice = null; // USB设备
        public static IDeviceNotifier UsbDeviceNotifier = DeviceNotifier.OpenDeviceNotifier(); // 打开设备通知
        System.Windows.Forms.Timer chartTimer = new System.Windows.Forms.Timer(); // 创建定时器
        public Form1()
        {
            InitializeComponent();
            InitChart();
        }
        private void Form1_Load(object sender, EventArgs e)
        {

        }
        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            CloseUSB();
        }
        private bool FindAndOpenUSB(int PID, int VID)
        {
            UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(PID, VID);
            UsbRegistry myUsbRegistry = UsbDevice.AllDevices.Find(MyUsbFinder);
            if (ReferenceEquals(myUsbRegistry, null))
            {
                MessageBox.Show("1");
                return false;
            }
            // Open this usb device.
            if (!myUsbRegistry.Open(out MyUsbDevice))
            {
                MessageBox.Show("2");
                return false;
            }
            ((LibUsbDevice)MyUsbDevice).SetConfiguration(1);
            ((LibUsbDevice)MyUsbDevice).ClaimInterface(0);
            MessageBox.Show(string.Format("Find Device:{0}", myUsbRegistry[SPDRP.DeviceDesc]));
            return true;
        }
        //关闭USB设备
        public void CloseUSB()
        {
            if (!ReferenceEquals(reader, null))
                reader.Dispose();
            if (!ReferenceEquals(writer, null))
                writer.Dispose();
            if (!ReferenceEquals(MyUsbDevice, null))
                MyUsbDevice.Close();
        }
        private void OnDeviceNotifyEvent(object sender, DeviceNotifyEventArgs e)
        {
            textBox1.Text = e.ToString();
            if (e.EventType == EventType.DeviceArrival)
            {
                textBox1.Text = string.Format("发现有新USB设备连接，PID = 0x{0:X},VID = 0x{1:X}.\r\n设备的详细信息{2}", e.Device.IdProduct, e.Device.IdVendor, e.Device.ToString());
                //看看目前新连接的USB设备是不是目标设备
                if (e.Device.IdProduct == myPID && e.Device.IdVendor == myVID)
                {
                    MessageBox.Show("该USB设备是目标设备");
                    //发现目标设备并打开该设备
                    FindAndOpenUSB(myPID, myVID);
                    reader = MyUsbDevice.OpenEndpointReader(ReadEndpointID.Ep01);
                    writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
                    if (EnableInt == true)
                    {
                        reader.DataReceived += (OnRxEndPointData);
                        reader.DataReceivedEnabled = true;
                    }
                }
                else
                {
                    MessageBox.Show("该USB设备不是目标设备\r\n");
                }
            }
            else if (e.EventType == EventType.DeviceRemoveComplete)
            {
                textBox1.Text = string.Format("发现有USB设备移除，PID = 0x{0:X}, VID = 0x{1:X}\r\n设备的详细信息{2}", e.Device.IdProduct, e.Device.IdVendor, e.Device.ToString());
                //看看目前移除的USB设备是不是目标设备
                if (e.Device.IdProduct == myPID && e.Device.IdVendor == myVID)
                {
                    MessageBox.Show(string.Format("移除的USB设备是目标设备\r\n"));
                    CloseUSB();
                }
                else
                {
                    MessageBox.Show(string.Format("移除的USB设备不是目标设备\r\n"));
                }
            }
        }
        private void button1_Click(object sender, EventArgs e)
        {
            if (button1.Text == "显示USB信息")
            {
                UsbDeviceNotifier.Enabled = true;
                UsbDeviceNotifier.OnDeviceNotify += OnDeviceNotifyEvent; // Hook the device notifier event
                Application.DoEvents();
                button1.Text = "关闭USB信息";
            }
            else
            {
                UsbDeviceNotifier.Enabled = false;  // Disable the device notifier
                UsbDeviceNotifier.OnDeviceNotify -= OnDeviceNotifyEvent; // Unhook the device notifier event
                button1.Text = "显示USB信息";
            }
        }
        private void OnRxEndPointData(object sender, EndpointDataEventArgs e)
        {
            MessageBox.Show(Encoding.Default.GetString(e.Buffer, 0, e.Count));
        }
        private void InitChart()
        {
            DateTime time = DateTime.Now;

            chartTimer.Interval = 1000;
            chartTimer.Tick += chartTimer_Tick;

            chart1.Click += chart1_Click;

            Series series = chart1.Series[0];
            series.ChartType = SeriesChartType.Spline;

            chart1.ChartAreas[0].AxisX.LabelStyle.Format = "HH:mm:ss";
            chart1.ChartAreas[0].AxisX.ScaleView.Size = 5;
            chart1.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
            chart1.ChartAreas[0].AxisX.ScrollBar.Enabled = true;

            //chartTimer.Start();
        }
        private void chart1_Click(object sender, EventArgs e)
        {
            chart1.ChartAreas[0].AxisX.ScaleView.Size = 5;
            chart1.ChartAreas[0].AxisX.ScrollBar.IsPositionedInside = true;
            chart1.ChartAreas[0].AxisX.ScrollBar.Enabled = true;
        }
        void chartTimer_Tick(object sender, EventArgs e)
        {
            Random ra = new Random();
            Series series = chart1.Series[0];
            series.Points.AddXY(DateTime.Now, ra.Next(1, 10));
            chart1.ChartAreas[0].AxisX.ScaleView.Position = series.Points.Count - 5;
        }
    }
}
